package com.douwong.student.task;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.PrepareBean;
import com.douwong.student.model.PrepareResource;
import com.douwong.student.model.RequestAction;
import com.douwong.student.model.StatusCode;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.UIUtils;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * 请求备课资源
 * 
 * @author leihuajie
 *
 */
public class PrepareResourceListTask extends AsyncTask<String, Integer, Integer> {

	private BaseApplication app;
	private WorkResultNotify<PrepareResource> workResult = null;
	private ArrayList<PrepareResource> listData = null;
	public static int NO_DATA = 0;// 没有新的数据
	public static int REQUESTOK = 1;// 加载更多
	public static int NO_NETWOK = -1;// 没有网络
	public static int ERROR = 2;
	private RequestAction action;
	private Context context;

	public PrepareResourceListTask(Context context, RequestAction action, BaseApplication app) {
		this.context = context;
		this.action = action;
		this.app = app;
	}

	public void setWorkStautsListener(WorkResultNotify<PrepareResource> workResult) {
		this.workResult = workResult;
	}

	@Override
	protected Integer doInBackground(String... params) {

		int resultCode = REQUESTOK;
		try {
			if (RequestAction.INIT == action) {//初始化
				try {
					listData = PrepareReaourceDBService.getInstance(context).queryResource(Integer.valueOf(params[1]));
					Log.e("size", listData.size()+"");
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (listData.size() > 0) {
					return resultCode;
				} else if (NetUtils.NetwrokIsUseful(UIUtils.getContext())) {
					resultCode = accessNetworkRequestData(params);
				} else {
					resultCode = NO_NETWOK;
				}
			} else if (NetUtils.NetwrokIsUseful(UIUtils.getContext())) {//判读是否有网络
				resultCode = accessNetworkRequestData(params);
			} else {
				resultCode = NO_NETWOK;
			}

		} catch (Exception e) {
			resultCode = ERROR;
		}

		return resultCode;

	}

	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);
		workResult.notify(result, listData);
	}

	private int accessNetworkRequestData(String... params) {

		String response = null;
		List<BasicNameValuePair> arrayParams = new ArrayList<BasicNameValuePair>();
		Log.e("classId", BaseApplication.sUserBean.getPersonalbean().getClassId()+"");
		arrayParams.add(new BasicNameValuePair("classId", BaseApplication.sUserBean.getPersonalbean().getClassId()+""));
		// arrayParams.add(new BasicNameValuePair("plType", "3"));
		arrayParams.add(new BasicNameValuePair("rows", "30"));
		arrayParams.add(new BasicNameValuePair("page", params[0]));
		// arrayParams.add(new BasicNameValuePair("leType", "3"));
		// arrayParams.add(new BasicNameValuePair("sourceType ", value));
		// arrayParams.add(new BasicNameValuePair("suffixType", params[1]));//1
		// 课件 ，2 教案，3 图片，4 影音，5 其他

		int resultCode = REQUESTOK;
		try {
			response = NetUtils.httpGet(NetConfig.PREPARE_RESOURCE_LIST, arrayParams);
			Log.e("response", response + "");
			StatusCode<PrepareBean> sc = (StatusCode<PrepareBean>) JSON.parseObject(response,
					new TypeReference<StatusCode<PrepareBean>>() {
					});
			if (sc != null && sc.isFlag()) {
				if ((sc.getData().getRows() == null || sc.getData().getRows().equals("")||sc.getData().getRows().equals("[]"))
						&& RequestAction.REFRESH == action) {
					PrepareReaourceDBService.getInstance(context).delete(Integer.valueOf(params[1]));
					return NO_DATA;
				}if ((sc.getData().getRows() == null || sc.getData().getRows().equals("")||sc.getData().getRows().equals("[]"))
						&& RequestAction.LOADMROE == action) {

					return NO_DATA;
				}
				listData = (ArrayList<PrepareResource>) JSON.parseArray(sc.getData().getRows(), PrepareResource.class);
				Log.e("listData.size()", listData.size()+"");
				if (listData == null) {
					return NO_DATA;
				}else if(listData.size()>0){
					if (action == RequestAction.LOADMROE) {
						addNewData(Integer.valueOf(params[1]));
					} else if (action == RequestAction.INIT) {
						addData();
					} else if (action == RequestAction.REFRESH) {
						updateData(Integer.valueOf(params[1]));
//						 PrepareReaourceDBService.getInstance(context).delete(Integer.valueOf(params[1]));
//						 addData();
					}
				}
				
			} else {
				return NO_DATA;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return resultCode;
	}

	private void addData() {
		new Thread() {

			@Override
			public void run() {
				super.run();
				for (PrepareResource pr : listData) {
					PrepareReaourceDBService.getInstance(context).add(pr);
				}
			}

		}.start();

	}

	private void addNewData(int suffix) {
		boolean isNew = true;
		ArrayList<PrepareResource> locaList = PrepareReaourceDBService.getInstance(context).queryResource(suffix);
		for (int i = 0; i < listData.size(); i++) {
			if (locaList.size() > 0) {
				for (int j = 0; j < locaList.size(); j++) {
					if (listData.get(i).getId() == locaList.get(j).getId()) {
						isNew = false;
						break;
					}
				}
				if (isNew) {
					PrepareReaourceDBService.getInstance(context).add(listData.get(i));
				} else {
					isNew = true;
				}
			}
		}
		listData = PrepareReaourceDBService.getInstance(context).queryResource(suffix);
		Log.e("listDatamore", ""+listData.size());
	}

	private void updateData(int suffix) {
		boolean isNew = true;
		ArrayList<PrepareResource> locaList = PrepareReaourceDBService.getInstance(context).queryResource(suffix);
		for (int i = 0; i < listData.size(); i++) {
			if (locaList!=null&&locaList.size() > 0) {
				for (int j = 0; j < locaList.size(); j++) {
					if (listData.get(i).getId() == locaList.get(j).getId()) {
						isNew = false;
						break;
					}
				}
				if (isNew) {
					PrepareReaourceDBService.getInstance(context).add(listData.get(i));
				} else {
					isNew = true;
				}
			}
		}
		boolean isExist=false;
		for (int i = 0; i < locaList.size(); i++) {
			if (locaList!=null&&locaList.size() > 0) {
				for (int j = 0; j < listData.size(); j++) {
					if (locaList.get(i).getId() == listData.get(j).getId()) {
						isExist = true;
						break;
					}
				}
				if (isExist) {
					isExist = false;
				} else {
					PrepareReaourceDBService.getInstance(context).deleteResource(locaList.get(i).getId());
				}
			}
		}
		listData = PrepareReaourceDBService.getInstance(context).queryResource(suffix);
		Log.e("listData", ""+listData.size());
	}

}
